<template>
	<PageContainer name="已有账号，去登录">
		<view class="register-container">
			<AccountForm v-model="form" :configs="configs">
				<template #code>
					<CodeInput :phone-number="form.phone" v-model="form.code" />
				</template>
			</AccountForm>
			<button class="global-submit-button" @click="submit">注 册</button>
			<Agreements v-model="isChecked" />
		</view>
	</PageContainer>
</template>

<script>
	import PageContainer from '@/components/PageContainer/PageContainer.vue';
	import AccountForm from '@/components/AccountForm/AccountForm.vue';
	import CodeInput from '@/components/AccountForm/CodeInput.vue';
	import Agreements from './components/Agreements/Agreements.vue';
	import {
		validatePhoneNumber
	} from '@/utils/validate.js';
	import {
		getCode,
		register,
	} from '@/api/login';
	export default {
		components: {
			PageContainer,
			Agreements,
			AccountForm,
			CodeInput,
		},
		data() {
			return {
				isChecked: false,
				form: {
					name: '',
					phone: '',
					code: '',
					password: '',
					newPassword: '',
				},
				configs: [{
						label: '昵称',
						prop: 'name',
						maxlength: 12,
					}, {
						label: '手机号',
						prop: 'phone',
						maxlength: 11,
					},
					{
						label: '验证码',
						prop: 'code',
						slot: 'code',
					},
					{
						label: '密码',
						prop: 'password',
						maxlength: 12,
					},
					{
						label: '确认密码',
						prop: 'newPassword',
						maxlength: 12,
					}
				],
			}
		},
		methods: {
			async submit() {
				const data = this.form;
				if (!data.name?.trim()) {
					uni.showToast({
						title: '请输入昵称',
						icon: 'none',
					})
					return;
				}
				if (!validatePhoneNumber(data.phone)) {
					return;
				}
				if (!data.password?.trim()) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none',
					})
					return;
				}
				if (data.password != data.newPassword) {
					uni.showToast({
						title: '两次密码不一致',
						icon: 'none',
					})
					return;
				}
				if (!data.code?.trim()) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none',
					})
					return;
				}
				if (!this.isChecked) {
					uni.showToast({
						title: '请先同意软件协议',
						icon: 'none',
					})
					return;
				}
				uni.showLoading({
					title: '正在注册',
					mask: true,
				})
				await register(data);
				uni.hideLoading();
				uni.showToast({
					title: '注册成功',
					icon: 'none',
				})
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/entrance/login',
					})
				}, 500)
			}
		}
	}
</script>

<style scoped lang="scss">
	.register-container {
		padding: 80rpx 60rpx 0;
		text-align: center;
	}
</style>